package com.edu.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import com.alibaba.fastjson.JSON;
import com.edu.entiy.History;
import com.edu.entiy.Page;
import com.edu.entiy.User;
import com.edu.service.HistoryService;
import com.edu.service.UserService;
import com.edu.service.impl.HistoryServiceImpl;
import com.edu.service.impl.UserServiceImpl;
import com.edu.utils.PageTool;
import com.edu.utils.PaginationUtils;
import com.edu.utils.ResBean;
@WebServlet("/userServlet/*")
public class UserServlet extends BaseServlet{
	private UserService userService = new UserServiceImpl();
	private HistoryService historyService = new HistoryServiceImpl();
	//修改用户框
	public void updUserInfo(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, InvocationTargetException, IOException {
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		String password = request.getParameter("password2");
		int result = userService.updatePass(user.getId(), password);
		if(result == 1) {
			//修改之后移除session
			session.removeAttribute("user");
			//跳转到登录页面
			response.sendRedirect("/books/login.jsp");
		}
	}
	//检查密码
	public void checkPass(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String oldpass = request.getParameter("password");
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		ResBean resBean = new ResBean();
		if(user.getPassword().equals(oldpass)) {
			resBean.setCode(200);
			resBean.setMessage("密码正确!");
			response.setContentType("application/json");
			String json = JSON.toJSONString(resBean);
			response.getWriter().write(json);
		}else {
			resBean.setCode(400);
			resBean.setMessage("密码错误!");
			response.setContentType("application/json");
			String json = JSON.toJSONString(resBean);
			response.getWriter().write(json);
		}
	}
	
	public void register(HttpServletRequest request, HttpServletResponse response) throws IOException, IllegalAccessException, InvocationTargetException {
		User user = new User();
		BeanUtils.populate(user, request.getParameterMap());
		user.setLendDayNum(15);
		user.setStatus(1);
		user.setLendMaxNum(5);
		userService.addUser(user);
		response.sendRedirect("/books/login.jsp");
	}
	public void checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		boolean result = false;
		//获取验证码
		HttpSession session = request.getSession();
		String code = (String)session.getAttribute("code");
		//获取输入的验证码
		String inputCode = request.getParameter("code");
		ResBean resBean = new ResBean();
		if(code.equalsIgnoreCase(inputCode)) {
			resBean.setCode(200);
			resBean.setMessage("验证码正确!");
			String  json = JSON.toJSONString(resBean);
			response.setContentType("application;text/json");
			response.getWriter().write(json);
			result = true;
		}else {
			resBean.setCode(400);
			resBean.setMessage("验证码错误!");
			String  json = JSON.toJSONString(resBean);
			response.setContentType("application;text/json");
			response.getWriter().write(json);
			result = false;
		}
	}
	//用户登录功能
	public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		//调用对应service层方法获取到查询结果
		User user = userService.login(userName, password);
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(60 * 30);
		if(user == null) {
			System.out.println("没查找该用户");
			request.setAttribute("state", "输入有误,请重新输入");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}else {
			//登陆成功,设置session,跳转页面
			session.setAttribute("user",user);
			response.sendRedirect("/books/index.jsp");		
		}

	}
	//查询所有
	public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		List<User> userList = userService.list();
		request.setAttribute("userList", userList);
		request.getRequestDispatcher("/admin/admin_user.jsp").forward(request, response);
	}
	//检查用户信息
	public void checkUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取添加用户的用户名
		String userName = request.getParameter("userName");
		System.out.println("看看用户名"+userName);
		//检查是否重复
		ResBean resBean = new ResBean();
		if(userService.selectUserByUserName(userName)) {
			//用户名重复
			resBean.setCode(400);
			resBean.setMessage("用户名不能重复");			
		}else {
			resBean.setCode(200);
			resBean.setMessage("账号可以使用");
		}
		String json = JSON.toJSONString(resBean);
		System.out.println(json);
		response.getWriter().write(json);
	}
	//添加用户
	public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException, IllegalAccessException, InvocationTargetException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		User user = new User();
		user.setTimes(0);
		BeanUtils.populate(user, request.getParameterMap());
		System.out.println(user);
		userService.addUser(user);
		request.getRequestDispatcher("userServlet/page").forward(request, response);
	}
	//分页查询
	public void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取传入的数据
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");
        PageTool<User> pageTool = userService.selectByPage(_currentPage, _pageSize);
        String pageResult =  PaginationUtils.getPagation(pageTool.getTotalCount(), pageTool.getCurrentPage(), pageTool.getPageSize(), "/userServlet/page");
        //存数据
        request.setAttribute("pageResult", pageResult);
        request.setAttribute("userList", pageTool.getRows());
        request.getRequestDispatcher("/admin/admin_user.jsp").forward(request, response);
	}
	//分页查询
	public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		 //获取传入的数据
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");
        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);
        Page<User> page = userService.selectByPage(currentPage, pageSize);
        request.setAttribute("pageList", page);
        //生成前端分页按钮
        request.getRequestDispatcher("/admin/admin_user.jsp").forward(request, response);
	}
	//修改用户
	public void updateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		System.out.println("修改中");
		User user = new User();
		try {
			BeanUtils.populate(user, request.getParameterMap());
			userService.updateUser(user);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		request.getRequestDispatcher("userServlet/page").forward(request, response);
	}
	
	//用户删除
	public void deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		String _id = request.getParameter("id");
		int id = Integer.parseInt(_id);
		History history = historyService.selectByuserId(id);
		if(history == null) {
			System.out.println("删除成功");
			userService.deleteUser(id);
			request.getRequestDispatcher("userServlet/page").forward(request, response);
		}else {
			System.out.println("删除失败");
			request.setAttribute("UserMes", 1);
			request.getRequestDispatcher("userServlet/page").forward(request, response);
		}
		boolean result =  userService.deleteUser(id);
		if(result) {
			request.getRequestDispatcher("userServlet/page").forward(request, response);
		}else {
			System.out.println("删除失败");
		}
	}
	public void orderByTimes(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 String _currentPage = request.getParameter("currentPage");
	     String _pageSize = request.getParameter("pageSize");
	     PageTool<User> pageTool  = userService.selectByPageOrderByTimes(_currentPage, _pageSize);
	     String pageResult = PaginationUtils.getPagation(pageTool.getTotalCount(),pageTool.getCurrentPage() , pageTool.getPageSize(), "/userServlet/orderByTimes");
	     request.setAttribute("userList",pageTool.getRows());
	     request.setAttribute("pageResult",pageResult);
	     HttpSession session = request.getSession();
	     User user = (User)session.getAttribute("user");
	     if(user.getStatus() == 2) {
	    	 request.getRequestDispatcher("/admin/admin_brtimes.jsp").forward(request, response);
	     }else {
	    	 request.getRequestDispatcher("/user/brtimes.jsp").forward(request, response);
	     }
	}
	public void selectByCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String word = request.getParameter("word");
		String _currentPage = request.getParameter("currentPage");
	    String _pageSize = request.getParameter("pageSize");
	    PageTool<User> pageTool  = userService.selectByPageOrderByTimes(_currentPage, _pageSize, word);
	     String pageResult = PaginationUtils.getPagation(pageTool.getTotalCount(),pageTool.getCurrentPage() , pageTool.getPageSize(), "/userServlet/orderByTimes");
	     request.setAttribute("userList",pageTool.getRows());
	     request.setAttribute("pageResult",pageResult);
	     HttpSession session = request.getSession();
	     request.getRequestDispatcher("/admin/admin_brtimes.jsp").forward(request, response);
	}
	
	public void updateUserPhone(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		System.out.println("修改中");
		HttpSession session=request.getSession();
		User user = (User) session.getAttribute("user");
		System.out.println(user);
		user.setNickname(request.getParameter("nickname"));
		user.setPhone(request.getParameter("phone"));
		userService.updateUserPhone(user);
		System.out.println(request.getParameter("nickname"));
		request.getRequestDispatcher("../index.jsp").forward(request, response);
		
	}


	
}
